import router from '@/router'
import { useUserStore } from '@/store'
import { RouteParamValue, RouteRecordName } from 'vue-router'
import { ProjectConfig } from '@/config/ProjectConfig'
import { mapConvertObj, objConvertMap } from '@/util'
const loginUrl = '/login'

const paramsMessageMap = new Map<RouteRecordName, RouteRecordName[]>()

function initParamsMessageMap() {
  const localLmStr = sessionStorage.getItem(ProjectConfig.LOCAL_LEAVING_MESSAGE)
  if (localLmStr) {
    try {
      const obj = JSON.parse(localLmStr)
      objConvertMap(obj, paramsMessageMap)
    } catch (e) {
      console.error(e)
    }
  }
}

export function silentLogin() {
  const store = useUserStore()

  initParamsMessageMap()

  router.beforeEach((to, from, next) => {
    // @ts-ignore
    if (paramsMessageMap.has(to.name)) {
      // @ts-ignore
      to.params.leaveMessage = paramsMessageMap.get(to.name)
    }
    // @ts-ignore
    if (paramsMessageMap.has(from.name)) {
      // @ts-ignore
      paramsMessageMap.delete(from.name)
      updateMap()
    }
    if (to.meta.notNeedLogin) {
      next()
    } else {
      // 这个地方与刷新时重新登陆逻辑不冲突
      // SilentLogin.ts 中的代码是在用户刷新后，在session中重新取出用户信息然后完成登录
      // 代码是在此之前执行

      store.hasLogin
        ? next()
        : next({
            path: loginUrl,
            query: {
              redirectTo: to.path,
              ...to.query
            }
          })
    }
  })
}

export function leavingMessageOnParams(name: RouteRecordName, msg: RouteParamValue | RouteParamValue[]) {
  // @ts-ignore
  paramsMessageMap.set(name, msg)
  updateMap()
}

function updateMap() {
  const jsonStr = JSON.stringify(mapConvertObj(paramsMessageMap))
  sessionStorage.setItem(ProjectConfig.LOCAL_LEAVING_MESSAGE, jsonStr)
}
